<template>
    <el-dialog title="授权角色" :visible.sync="isVisible">
        <el-form ref="authRoleForm" :model="authRoleForm" :rules="rules" label-width="100px">
            <el-form-item label="角色">
                <el-checkbox-group v-model="authRoleForm.roleId">
                    <el-checkbox v-for="(item, index) in roleData" :key="index" :label="item.id">{{item.name}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" plain size="small" @click="submitForm('authRoleForm')">保存</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script>

import userRoleApi from '@/api/system/userRole'
import roleApi from '@/api/system/role'
export default {
    name: 'AuthRole',
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            roleData: [], // 所有角色数据
            authRoleForm: {
                roleId: [], // 用户的角色ids
                userId: ''
            },
            rules: {
            }
        }
    },
    computed: {
        isVisible: {
            get() {
                return this.dialogVisible
            },
            set() {
                this.close()
            }
        }
    },
    methods: {
        close() {
            this.$emit('close')
        },
        submitForm() {
            userRoleApi.saveUserRole(this.authRoleForm).then(() => {
                this.isVisible = false
            })
        },
        getUserRole(id) { // 获取用户角色
            // 清空表单
            this.resetForm('authRoleForm')
            // 回显数据

            // 查询所有角色
            roleApi.query({}).then(res => {
                this.roleData = res.data.data
            })

            // 查询用户的角色
            this.authRoleForm.userId = id
            userRoleApi.query({'userId': id}).then(res => {
                this.authRoleForm.roleId = res.data.data.map(item => item.roleId)
            })

        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
        }
    }
}
</script>
